
<script lang="ts" setup>

import type { SwitchProps,SwitchEmits } from './types';
import {computed, onMounted, ref, watch} from 'vue'

defineOptions({
  name:'WkSwitch',
  inheritAttrs:false,// 取消默认的额外属性挂载
})
const props = defineProps<SwitchProps>()
const Emits = defineEmits<SwitchEmits>()
const checkboxRef = ref<HTMLInputElement>()

// 代表组件是否选中的变量 innerValue，来源于 props
const innerValue = ref<boolean>(props.modelValue)
// 看起来多一步画蛇添足，到后面 modelValue 的类型不是Boolean的时候就很有用了
const isChecked = computed(()=>{
  return innerValue.value
})
// 需要时刻监听
watch(props,(value)=>{
  innerValue.value = props.modelValue 
},{
  deep:true
})
watch(innerValue,(val)=>{
  Emits('change',innerValue.value)
  Emits('update:modelValue',innerValue.value)
})
const switchValue = ()=>{
  if(props.disabled)return 
  innerValue.value = !innerValue.value
  Emits('change',innerValue.value)
  Emits('update:modelValue',innerValue.value)
}
onMounted(()=>{
  checkboxRef.value!.checked = innerValue.value
})
watch(innerValue,()=>{
  checkboxRef.value!.checked = innerValue.value
  console.log('check:',checkboxRef.value!.checked,' , inner:',innerValue.value)
})
</script>
<template>
<div

class="wk-switch"
:class="{
  [`wk-switch--${size}`]:size,
  'is-disabled':disabled,
  'is-checked':isChecked,
}">
<!-- 复选框 -->
<input

ref="checkboxRef"
class="wk-switch__input"
@keydown.space="switchValue"
type="checkbox"
role="switch"
:name="name"
:disabled="disabled"
/>
<!-- 长方形 -->
<div 
@click="switchValue"
class="wk-switch__core"> 
  <!-- 圆 -->
  <div class="wk-switch__core-action"></div>
</div>
</div>
</template>
<style scoped>

</style>